import 'package:shared_preferences/shared_preferences.dart';
import 'package:safety_platform/models/login_user.dart';
import 'package:oauth2/oauth2.dart' as oauth2;
import 'dart:io';
import 'dart:convert';
// import './http.dart' show mainUrl;

var mainUrl = 'http://www.safety-saas.com';

final identifier = "biSNqztvIm9QW4GqCNHoTwWBiTrpq89M9xFjnq3J";
final secret =
    "v2J5dobvIPYJLuVHNOlvYFWfAnhUokY1TppV1t5DHDKXJXAcW8kSMdzN6NKfrPZuSJLt62TVDV1HKX0sNEmreZPr7iplJ7CuxtLVUvQd8YbV1U1tlBYCc0anLJsrh6u4";

final username = "182828282828";
final password = "-1234Asdf";
final tokenEndpoint = Uri.parse("$mainUrl/oauth/token/");
final userInfo = Uri.parse("$mainUrl/api/auths/info/");
final defaultHeaders = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
};

LoginUser _currentUser = null;
oauth2.Client _client = null;

String _userInfo = null;
Future<Null> login(String loginName, String password) async {
  try {
    _client = await oauth2.resourceOwnerPasswordGrant(
        tokenEndpoint, loginName, password,
        identifier: identifier, secret: secret);
    setToken(_client.credentials.toJson());
    setLastUser(loginName);
    var res = await _client.get(userInfo, headers: defaultHeaders);
    print('auth: ${res.statusCode}');
    if (res.statusCode == 200) {
      Encoding encoding = Encoding.getByName('utf-8');
      var body = encoding.decode(res.bodyBytes);
      _currentUser = LoginUser.fromJson(json.decode(body));
      await setUserInfo(body);
    } else {
      throw Exception('服务器错误');
    }
  } on oauth2.AuthorizationException catch (ae) {
    print('登录错误: $ae');
    throw Exception('用户或密码不正确');
  }
}

LoginUser getCurrentUser() {
  return _currentUser;
}

Future<bool> getUser() async {
  String tokenString = await getToken();
  if (tokenString != null) {
    oauth2.Credentials credentials = oauth2.Credentials.fromJson(tokenString);
    print('token ${credentials.isExpired}');
    if (credentials.isExpired) {
      if (!credentials.canRefresh) {
        var token = credentials.refresh(identifier: identifier, secret: secret);
        await setToken(token);
        return true;
      } //todo refresh token
    } else {
      String str = await getUserInfo();
      if (str == null) {
        return true;
      }
      _currentUser = LoginUser.fromJson(json.decode(str));
      return false;
    }
  }

  return true;
}

Future<String> getUserInfo() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('__user_info');
}

Future<String> getToken() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String token = prefs.getString("__token");
  print("token String $token");
  return token;
}

Future<String> getAccessToken() async {
  String token = await getToken();

  if (token != null) {
    oauth2.Credentials credentials = oauth2.Credentials.fromJson(token);
    if (!credentials.isExpired) {
      return credentials.accessToken;
    }
  }
  return null;
}

Future<Null> setUserInfo(String userInfo) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString("__user_info", userInfo);
  _userInfo = userInfo;
}

Future<String> getLastUser() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString("__last_user");
}

Future<Null> setToken(token) async {
  SharedPreferences pref = await SharedPreferences.getInstance();
  pref.setString("__token", token);
}

Future<Null> setLastUser(String userName) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString("__last_user", userName);
  return userName;
}
